package com.ugoodtech.mdcc.client.controller;

        /* Copyright (C) Ugoodtech, Inc - All Rights Reserved.
         * Unauthorized copying of this file, via any medium is strictly prohibited.
         * Proprietary and confidential.
         * Written by Stone Shaw.
         */

import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.ugoodtech.mdcc.client.dto.JsonResponse;
import com.ugoodtech.mdcc.client.service.AliSmsProvider;
import com.ugoodtech.mdcc.client.service.UserService;
import com.ugoodtech.mdcc.core.domain.User;
import com.ugoodtech.mdcc.core.domain.OpenIdParam;
import com.ugoodtech.mdcc.core.domain.VCode;
import com.ugoodtech.mdcc.core.repository.UserRepository;
import com.ugoodtech.mdcc.core.repository.GeneralCodeRepository;
import com.ugoodtech.mdcc.core.repository.OpenIdParamRepository;
import com.ugoodtech.mdcc.core.repository.VCodeRepository;
import com.ugoodtech.mdcc.core.service.WechatService;
import io.swagger.annotations.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import java.security.Principal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

@Api(description = "设置接口")
@RestController
@RequestMapping("/settings")
public class SettingController {

    @Value("${service.type}")
    private String serviceType;
    @Value("${service.version}")
    private String serviceVersion;

    @Autowired
    UserRepository userRepository;

    @Autowired
    UserService userService;


    @Autowired
    private AliSmsProvider aliSmsProvider;

    @Autowired
    GeneralCodeRepository generalCodeRepository;


    @Autowired
    private VCodeRepository vCodeRepository;

    @Autowired
    OpenIdParamRepository openIdParamRepository;


    @Autowired
    WechatService wechatService;


    @Value("${oss.base.url}")
    private String ossBaseUrl;
    @Value("${oss.bucket.name}")
    private String ossBucketName;
    @Value("${oss.AccessKeyID}")
    private String ossAccessKeyID;
    @Value("${oss.AccessKeySecret}")
    private String ossAccessKeySecret;
    @Value("${oss.endpoint}")
    private String ossEndPoint;

    @ApiOperation("获取系统版本")
    @RequestMapping(value = "/getSystemVersion", method = RequestMethod.GET)
    public JsonResponse getSystemVersion(
//            Principal principal
    ) {
        Map<String, String> map = new HashMap();
        map.put("serviceVersion", serviceVersion);
        map.put("serviceType", serviceType);
        return JsonResponse.successResponseWithData(map);
    }

    @ApiOperation("获取OSS相关参数")
    @RequestMapping(value = "/getOssSettings", method = RequestMethod.GET)
    public JsonResponse getOssSettings(
            Principal principal
    ) {
        Map<String, String> map = new HashMap();
        map.put("ossEndPoint", ossEndPoint);
        map.put("ossBaseUrl", ossBaseUrl);
        map.put("ossBucketName", ossBucketName);
        map.put("ossAccessKeyID", ossAccessKeyID);
        map.put("ossAccessKeySecret", ossAccessKeySecret);
        return JsonResponse.successResponseWithData(map);
    }

    @ApiOperation("获取验证码")
    @RequestMapping(value = "/getVCode", method = RequestMethod.GET)
    public JsonResponse getVCode(
            @ApiParam("手机号") @RequestParam String telephone) {
        User user = userRepository.findByUsername(telephone);
        if (user == null) {
            return JsonResponse.errorResponseWithError("抱歉", "手机号未注册过");
        }
        if (user.isEnabled() == false) {
            return JsonResponse.errorResponseWithError("抱歉", "此用户已被禁用");
        }

        int validationCode = new Random().nextInt(9999 - 1000 + 1) + 1000;
        try {
            SendSmsResponse sendSmsResponse = aliSmsProvider.sendSms(telephone, validationCode);
            logger.info("Send sms result is [{}], [{}].", sendSmsResponse.getCode(), sendSmsResponse.getMessage());
            if (null != sendSmsResponse) {
//                request.getSession().setAttribute(telephone, validationCode+"");
                VCode vCode = vCodeRepository.findByTelephone(telephone);
                if (null == vCode) {
                    vCode = new VCode();
                    vCode.setTelephone(telephone);
                }
                vCode.setvCode(validationCode + "");
                vCode.setUpdateTime(new Date());
                vCodeRepository.save(vCode);
                return JsonResponse.successResponse();
            } else {
                return JsonResponse.errorResponseWithError("fail", "验证码发送失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResponse.errorResponseWithError("fail", "验证码发送失败");
        }
    }

    @ApiIgnore
    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public JsonResponse register(
            String telephone,
            String vCode,
            String password,
            HttpServletRequest request
    ) {
        User user = userRepository.findByUsername(telephone);
        if (null == user) {
            return JsonResponse.errorResponseWithError("该手机号未绑定", "该手机号未绑定");
        }
        String telephoneCode = (String) request.getSession().getAttribute(telephone);
        if (vCode == null || !vCode.equals(telephoneCode)) {
            return JsonResponse.errorResponseWithError("验证码错误", "验证码错误");
        }
        if (user.isEnabled()) {
            return JsonResponse.errorResponseWithError("该用户已注册", "该用户已注册");
        }
        user.setEnabled(true);
        userService.changePassword(user, password);
        return JsonResponse.successResponse();
    }

    @ApiIgnore
    @RequestMapping(value = "/forgetPassword", method = RequestMethod.POST)
    public JsonResponse getVCode(
            String telephone,
            String vCode,
            String password,
            HttpServletRequest request
    ) {
        User user = userRepository.findByUsername(telephone);
        if (null == user) {
            return JsonResponse.errorResponseWithError("该手机号未绑定", "该手机号未绑定");
        }
        String telephoneCode = (String) request.getSession().getAttribute(telephone);
        if (vCode == null || !vCode.equals(telephoneCode)) {
            return JsonResponse.errorResponseWithError("验证码错误", "验证码错误");
        }
        userService.changePassword(user, password);
        return JsonResponse.successResponse();
    }


    @ApiOperation("基于code取openId")
    @RequestMapping(value = "/getOpenIdByCode", method = RequestMethod.GET)
    @ApiResponses({
            @ApiResponse(code = 200, message = "data", response = Boolean.class)
    })
    public JsonResponse getOpenIdByCode(
            @ApiParam(value = "openId的code", required = true) @RequestParam String code) throws Exception {
        return JsonResponse.successResponseWithData(wechatService.getOpenId(code));
    }

    @ApiOperation("基于openId存参数")
    @RequestMapping(value = "/saveOpenIdParam", method = RequestMethod.POST)
    @ApiResponses({
            @ApiResponse(code = 200, message = "data", response = Boolean.class)
    })
    public JsonResponse saveOpenIdParam(
            @ApiParam(value = "openId", required = true) @RequestParam String openId,
            @ApiParam @RequestParam(required = false) String user_token,
            @ApiParam @RequestParam(required = false) String user_loginBool,
            @ApiParam @RequestParam(required = false) String client_token,
            @ApiParam @RequestParam(required = false) String client_loginBool) {
        OpenIdParam openIdParam = openIdParamRepository.findByOpenId(openId);
        if (null == openIdParam) {
            openIdParam = new OpenIdParam();
        }
        openIdParam.setOpenId(openId);
        if (StringUtils.isNotEmpty(user_token)) {
            openIdParam.setUser_token(user_token);
        }
        if (StringUtils.isNotEmpty(user_loginBool)) {
            openIdParam.setUser_loginBool(user_loginBool);
        }
        if (StringUtils.isNotEmpty(client_token)) {
            openIdParam.setClient_token(client_token);
        }
        if (StringUtils.isNotEmpty(client_loginBool)) {
            openIdParam.setClient_loginBool(client_loginBool);
        }
        openIdParamRepository.save(openIdParam);
        return JsonResponse.successResponseWithData(openIdParam);
    }

    @ApiOperation("基于openId取参数")
    @RequestMapping(value = "/getOpenIdParam", method = RequestMethod.GET)
    @ApiResponses({
            @ApiResponse(code = 200, message = "data", response = Boolean.class)
    })
    public JsonResponse getOpenIdParam(
            @ApiParam(value = "openId", required = true) @RequestParam String openId
    ) {
        OpenIdParam openIdParam = openIdParamRepository.findByOpenId(openId);
        return JsonResponse.successResponseWithData(openIdParam);
    }


    Logger logger = LoggerFactory.getLogger(SettingController.class);
}
